//
//  PostSender.m
//  KOP
//
//  Created by 王贵源 on 15/9/24.
//  Copyright © 2015年 王贵源. All rights reserved.
//

#import "PostSender.h"
#import "DGJNilStr.h"
//#import "AFNetworkActivityIndicatorManager.h"
//#import "AFNetworkReachabilityManager.h"

@interface PostSender()<NSURLConnectionDataDelegate>


@end
@implementation PostSender{
    BOOL finished;
    


}

- (void)sendTo:(NSString *)url data:(NSMutableDictionary *)paras header:(NSMutableDictionary *)header{
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                            cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                        timeoutInterval:10];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
    NSString *postStr = @"";
    NSArray * keys = [paras allKeys];
    for(int i=0;i<[keys count];i++)//普通参数
    {
        NSString *key=[keys objectAtIndex:i];
        postStr = [NSString stringWithFormat:@"%@&%@=%@",postStr,key,[paras objectForKey:key]];
    }
    if ([DGJNilStr isBlankString:postStr]) {
        postStr = @"&";
    }
    NSData *postData = [[postStr substringFromIndex:1] dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postData];//设置参数
    
    //处理 header
    if (header) {
        NSArray * headerKeys = [header allKeys];
        for(int i=0;i<[headerKeys count];i++){
            NSString *key=[headerKeys objectAtIndex:i];
            [request setValue:[header objectForKey:key] forHTTPHeaderField:key];
        }
    }
    
    //    NSHTTPURLResponse *response = nil;
    //    NSError *error = nil;
    //    NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //    NSString *resultStr = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
    //    NSMutableDictionary * target = [[NSMutableDictionary alloc] init];
    //
    //    //组装返回
    //    if (response) {
    //        [target setValue:[response allHeaderFields] forKey:@"headers"];
    //    }
    //    if (error) {
    //        [target setValue:error forKey:@"error"];
    //    }
    //
    //    [target setValue:resultStr forKey:@"result"];
    //
    //
    //    return target;
    
    
//    AFNetworkReachabilityManager *reachManager =
//    [AFNetworkReachabilityManager sharedManager];
//    // 2.设置网络状态改变后的处理
//    [reachManager startMonitoring];
//    //FIXME  提示网络状态
//    [reachManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        // 当网络状态改变了, 就会调用这个block
//        switch (status) {
//            case AFNetworkReachabilityStatusUnknown: // 未知网络
//                NSLog(@"未知网络");
//                break;
//                
//            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
//                NSLog(@"没有网络(断网)");
//                break;
//                
//            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
//            {NSLog(@"手机自带网络");
//                //链接服务器
//                NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//                NSLog(@"手机网络链接服务器 == %@",connection);
//            } break;
//                
//            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
//            {
//                NSLog(@"WIFI");
//                //链接服务器
//                NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//                NSLog(@"WIFI链接服务器 == %@",connection);
//            }break;
//        }
//    }];

    //链接服务器
//    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//    NSLog(@"链接服务器 == %@",connection);
    while(!finished) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        
    }
}
//接收到服务器回应的时候调用此方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSHTTPURLResponse *res = (NSHTTPURLResponse*)response;
    _receiveData = [NSMutableData data];//数据存储对象的的初始化
    _dataPackSerialNo=0;
    NSLog(@"收到服务器回应 ＝＝ %@",[res allHeaderFields]);
    [self.resultDic setValue:[res allHeaderFields] forKey:@"headers"];
}
//接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_receiveData appendData:data];
    NSLog(@"收到服务器传回的数据包，数据包序号：%d",self.dataPackSerialNo);
    _dataPackSerialNo += 1;
}
//数据传输完之后调用此方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"数据传输完成，输出所有数据结果。。。");
    NSString *receiverStr = [[NSString alloc]initWithData:_receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",receiverStr);
    [self.resultDic setValue:receiverStr forKey:@"result"];
    //发送数据
    [self.postDelegate sendresultDic:self.resultDic];
    finished = TRUE;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"网络请求出错：%@",error);
    [self.resultDic setValue:error forKey:@"error"];
}
- (NSMutableDictionary *)resultDic{
    if (!_resultDic) {
        _resultDic = [[NSMutableDictionary alloc]initWithCapacity:0];
    }
    return _resultDic;
    
}
@end
